package com.eagle.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.FormElement;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtext.client.core.Connection;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Margins;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.Node;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.dd.DD;
import com.gwtext.client.dd.DDProxy;
import com.gwtext.client.dd.DragData;
import com.gwtext.client.dd.DragSource;
import com.gwtext.client.dd.DropTarget;
import com.gwtext.client.dd.DropTargetConfig;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.MessageBoxConfig;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.Viewport;
import com.gwtext.client.widgets.WaitConfig;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GridView;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;
import com.gwtext.client.widgets.layout.FitLayout;
import com.gwtext.client.widgets.menu.Menu;
import com.gwtext.client.widgets.tree.AsyncTreeNode;
import com.gwtext.client.widgets.tree.TreeDragData;
import com.gwtext.client.widgets.tree.TreeNode;
import com.gwtext.client.widgets.tree.TreePanel;
import com.gwtext.client.widgets.tree.XMLTreeLoader;
import com.gwtext.client.widgets.tree.event.TreeNodeListenerAdapter;
import com.gwtextux.client.widgets.upload.SwfUploadPanel;
import com.ssc.osa.osawt.workspace.client.core.AjaxUtil;

public class DemoControlPanel implements EntryPoint
{
    private Panel workspace = null;
    private Panel borderPanel = null;

    private Panel westPanel;
    private TabPanel westTabPanel;

    private Panel eastPanel;
    private TabPanel eastTabPanel;

    private Panel southPanel;
    private TabPanel southTabPanel;

    private Panel centerPanel;
    private TabPanel centerTabPanel;

    private boolean addSouth = true;
    private boolean addEast = true;
    private boolean addWest = true;
    private boolean plainPanels = false;

    private int minSouthHeight = 100;
    private int maxSouthHeight = 300;
    private boolean southMinMode = false;

    private TreeNodeListenerAdapter treeNodeListenerAdapter = new TreeNodeListenerAdapter()
    {
	@Override
	public void onClick(Node node, EventObject e)
	{
	    super.onClick(node, e);
	    TreeNode treeNode = (TreeNode) node;
	    // String[] props = teeNode.getProperties();
	    // if(null == props){
	    // return;
	    // }
	    // String result = "";
	    // for (int i = 0; i < props.length; i++)
	    // {
	    // String value = node.getAttribute(props[i]);
	    // if(null!=value&&value.length()>0){
	    // result=result+props[i]+":"+value+"\n||&nbsp;";
	    // }
	    // }

	    // MessageBox.alert("this is " + treeNode.getText() + ",id:" +
	    // node.getId());

	    genMessageBox(treeNode.getText());
	}

	@Override
	public void onContextMenu(Node node, EventObject e)
	{
	    super.onContextMenu(node, e);
	    Menu menu = new Menu();
	    // TODO
	}

	@Override
	public void onDblClick(Node node, EventObject e)
	{
	    super.onDblClick(node, e);
	    MessageBox.hide();
	}

    };

    public DemoControlPanel()
    {
	// create the mainPanel
	createWorkspace();

	// create the borderPanel
	createBorderPanel();

	// south
	// southTabPanel = new TabPanel();
	// southTabPanel.setDefaults(new DefaultsHandler()
	// {
	// public void apply(Component component)
	// {
	// component.setHideMode("offsets");
	// }
	// });
	// southTabPanel.setBorder(false);

	southPanel = new Panel();
	southPanel.setHeight(180);
	southPanel.setBorder(false);
	southPanel.setCollapsible(true);
	southPanel.setLayout(new BorderLayout());
	// if (!plainPanels)
	// {
	// southPanel.add(southTabPanel);
	// }

	// south panel content

	// Object[][] states = new Object[][]
	// { new Object[]
	// { "AL", "Alabama","desc1" }, new Object[]
	// { "AK", "Alaska","desc2" }, new Object[]
	// { "AZ", "Arizona","desc3" }, new Object[]
	// { "AR", "Arkansas","desc4" }, new Object[]
	// { "CA", "California","desc5" } };
	// ArrayReader reader = new ArrayReader(new RecordDef(new FieldDef[]
	// { new StringFieldDef("abbr","0"), new StringFieldDef("state","2"),
	// new StringFieldDef("nick","1") }));
	// final Store store = new Store(new MemoryProxy(states), reader);

	final Store store = new SimpleStore(new String[]
	{ "abbr", "state", "nick" }, SampleData.getStates());

	store.load();
	ColumnModel columnModel = new ColumnModel(new ColumnConfig[]
	{ new ColumnConfig("ABBR", "abbr", 50), new ColumnConfig("STATE", "state", 50), new ColumnConfig("NICK", "nick", 150) });

	final GridPanel gridPanel = new GridPanel();
	gridPanel.setTitle("Countries");
	gridPanel.setColumnModel(columnModel);
	gridPanel.setStore(store);
	gridPanel.setWidth(300);
	gridPanel.setHeight(200);
	gridPanel.setEnableDragDrop(true);

	BorderLayoutData southGridData = new BorderLayoutData(RegionPosition.CENTER);
	southGridData.setMargins(3, 0, 3, 3);
	// southPanel.add(gridPanel, southGridData);

	SwfUploadPanel sup = new SwfUploadPanel(store, columnModel);
	sup.setTitle("title");
	southPanel.add(sup, southGridData);

	DropTargetConfig config = new DropTargetConfig();
	config.setdDdGroup("ddGroup");

	DropTarget target = new DropTarget(gridPanel, config)
	{
	    @Override
	    public boolean notifyDrop(DragSource source, EventObject e, DragData data)
	    {
		if (!(data instanceof TreeDragData))
		{
		    return false;
		}
		// MessageBox.alert("source class:"+source.getClass()+"
		// event:"+e+" data class:"+data.getClass());
		TreeDragData treeDragData = (TreeDragData) data;
		TreeNode treeNode = treeDragData.getTreeNode();
		treeNode.remove();
		GridView gv = gridPanel.getView();
		int droppedRow = gv.findRowIndex(e);
		RecordDef rd = new RecordDef(new FieldDef[]
		{ new StringFieldDef("abbr", "0"), new StringFieldDef("state", "2"), new StringFieldDef("nick", "1") });
		Record record = rd.createRecord(new Object[]
		{ treeNode.getText(), treeNode.getText(), treeNode.getText() });
		if (droppedRow == -1)
		{
		    store.add(record);
		}
		else
		{
		    store.insert(droppedRow, record);
		}
		return true;
	    }
	};

	// east
	eastTabPanel = new TabPanel();
	eastTabPanel.setBorder(false);

	eastPanel = new Panel();
	eastPanel.setCollapsible(true);
	eastPanel.setWidth(200);
	eastPanel.setLayout(new BorderLayout());
	if (!plainPanels)
	{
	    eastPanel.add(eastTabPanel);
	}

	// east panel content
	TreePanel eastXmlTreePanel = new TreePanel();
	XMLTreeLoader xmlTreeLoader = new XMLTreeLoader();
	xmlTreeLoader.setDataUrl("data/countries.xml");
	xmlTreeLoader.setMethod(Connection.GET);
	xmlTreeLoader.setRootTag("countries");
	xmlTreeLoader.setFolderIdMapping("@id");
	xmlTreeLoader.setLeafIdMapping("@id");
	xmlTreeLoader.setFolderTitleMapping("@title");
	xmlTreeLoader.setFolderTag("team");
	xmlTreeLoader.setLeafTitleMapping("@title");
	xmlTreeLoader.setLeafTag("country");
	xmlTreeLoader.setQtipMapping("@qtip");
	xmlTreeLoader.setCheckedMapping("@checked");
	xmlTreeLoader.setIconMapping("@icon");
	xmlTreeLoader.setAttributeMappings(new String[]
	{ "@rank" });

	AsyncTreeNode rootNode = new AsyncTreeNode("Countries", xmlTreeLoader);
	eastXmlTreePanel.setRootNode(rootNode);
	eastXmlTreePanel.expandAll();

	BorderLayoutData eastXmlTreeData = new BorderLayoutData(RegionPosition.CENTER);
	eastXmlTreeData.setMargins(3, 0, 3, 3);
	eastPanel.add(eastXmlTreePanel, eastXmlTreeData);

	// west
	westTabPanel = new TabPanel();
	westTabPanel.setBorder(false);

	westPanel = new Panel();
	westPanel.setCollapsible(true);
	westPanel.setWidth(200);
	westPanel.setBorder(true);
	westPanel.setLayout(new BorderLayout());
	if (!plainPanels)
	{
	    westPanel.add(westTabPanel);
	}

	// west panel content
	TreePanel westTreePanel = new TreePanel();

	// enable the drag drop
	westTreePanel.setEnableDD(true);
	westTreePanel.setDdGroup("ddGroup");

	TreeNode rootTreeNode = genOneTreeNode("ROOT");
	westTreePanel.setRootNode(rootTreeNode);

	TreeNode generation1childNodeA = genOneTreeNode("A");
	rootTreeNode.appendChild(generation1childNodeA);

	TreeNode generation2childNodeA = genOneTreeNode("a");
	generation1childNodeA.appendChild(generation2childNodeA);

	TreeNode generation2childNodeB = genOneTreeNode("b");
	generation1childNodeA.appendChild(generation2childNodeB);

	TreeNode generation3childNodeA = genOneTreeNode("1");
	generation2childNodeB.appendChild(generation3childNodeA);

	TreeNode generation1childNodeB = genOneTreeNode("c");
	rootTreeNode.appendChild(generation1childNodeB);

	westTreePanel.expandAll();

	BorderLayoutData westTreeData = new BorderLayoutData(RegionPosition.CENTER);
	westTreeData.setMargins(3, 0, 3, 3);
	westPanel.add(westTreePanel, westTreeData);

	// center
	centerTabPanel = new TabPanel();
	centerTabPanel.setBorder(false);
	centerTabPanel.setEnableTabScroll(true);

	centerPanel = new Panel();
	// DD dd = new DD(centerPanel);
	DD dd = new DDProxy(centerPanel);
	centerPanel.setBorder(false);
	centerPanel.setLayout(new BorderLayout());
	if (!plainPanels)
	{
	    centerPanel.add(centerTabPanel);
	}

	// add TabPanel to centerPanel
	TabPanel tabPanel = new TabPanel();
	// tabPanel.setDraggable(true);
	tabPanel.add(createCommonTabPanel("word"));
	tabPanel.add(createCommonTabPanel("sentence"));
	tabPanel.add(createCommonTabPanel("article"));
	BorderLayoutData centerTabPanelData = new BorderLayoutData(RegionPosition.CENTER); // must
	// set
	// the
	// center
	// layout
	centerTabPanelData.setMargins(3, 0, 3, 3);
	tabPanel.setResizeTabs(true);
	tabPanel.setActiveItem(0);
	centerPanel.add(tabPanel, centerTabPanelData);

	borderPanel.add(centerPanel, new BorderLayoutData(RegionPosition.CENTER));

	// Timer timer = new Timer()
	// {
	// public void run()
	// {
	// MessageBox.hide();
	// }
	// };
	// timer.schedule(8000);

    }

    private TreeNode genOneTreeNode(String text)
    {
	TreeNode generation1childNodeA = new TreeNode(text);
	generation1childNodeA.addListener(treeNodeListenerAdapter);
	return generation1childNodeA;
    }

    private void genMessageBox(final String title)
    {
	MessageBox.show(new MessageBoxConfig()
	{
	    {
		setMsg("your operation is being handled, please wait...");
		setProgressText("Handling " + title + "...");
		setWidth(600);
		setWait(true);
		setWaitConfig(new WaitConfig()
		{
		    {
			setInterval(200);
		    }
		});
		setModal(false);
		setClosable(true);
	    }
	});
    }

    private Panel createCommonTabPanel(final String title)
    {
	Panel pl = new Panel(title);
	// pl.setDraggable(true); //can not set the draggable true otherwise
	// null
	pl.setAutoScroll(true);
	pl.addListener(new PanelListenerAdapter()
	{
	    @Override
	    public void onActivate(Panel panel)
	    {
		MessageBox.alert(title + " clicked");
		// genMessageBox(title);
		// Window.open("http://developer.mozilla.org/en/docs/DOM:window.open",
		// "_blank", "");
	    }

	});
	return pl;
    }

    public void onModuleLoad()
    {

	try{
	// final ProgressBar progressBar = new ProgressBar(20
	// ,ProgressBar.SHOW_TIME_REMAINING
	// +ProgressBar.SHOW_TEXT);
	// progressBar.setText("Doing something...");
	// RootPanel.get().add(progressBar);
	// Timer t = new Timer() {
	// public void run() {
	// int progress = progressBar.getProgress()+4;
	// if (progress>100) cancel();
	// progressBar.setProgress(progress);
	// }
	// };
	// t.scheduleRepeating(1000);

	String url = "/";

	FormElement formElement = Document.get().createFormElement();
	formElement.setAction(url);
	formElement.setName("ThisActionName");
	formElement.setMethod("post");
	Document.get().appendChild(formElement);

	formElement.submit();

	// add south panel
	if (isSouthPanelVisible())
	{
	    BorderLayoutData southData = new BorderLayoutData(RegionPosition.SOUTH);
	    southData.setMinSize(minSouthHeight);
	    if (southMinMode)
		southData.setMaxSize(minSouthHeight);
	    else
		southData.setMaxSize(maxSouthHeight);
	    southData.setMargins(new Margins(0, 0, 0, 0));
	    southData.setSplit(true);
	    southData.setCollapseModeMini(true);
	    borderPanel.add(southPanel, southData);
	}

	if (isEastPanelVisible())
	{
	    BorderLayoutData eastData = new BorderLayoutData(RegionPosition.EAST);
	    eastData.setSplit(true);
	    eastData.setMinSize(175);
	    eastData.setMaxSize(400);
	    eastData.setMargins(new Margins(0, 0, 5, 0));
	    eastData.setCollapseModeMini(true);
	    borderPanel.add(eastPanel, eastData);
	}

	if (isWestPanelVisible())
	{
	    BorderLayoutData westData = new BorderLayoutData(RegionPosition.WEST);
	    westData.setSplit(true);
	    westData.setMinSize(175);
	    westData.setMaxSize(400);
	    westData.setMargins(new Margins(0, 5, 0, 0));
	    westData.setCollapseModeMini(true);
	    borderPanel.add(westPanel, westData);
	}

	workspace.add(borderPanel);

	if (AjaxUtil.isStruts())
	{
	    RootPanel.get("__workspace").add(workspace);
	    // 28 pixels is the height of menu bar of ehorizon. Refer to
	    // ehorizon.css file in WAF
	    workspace.setSize(Window.getClientWidth(), Window.getClientHeight() - 28);
	}
	else
	{
	    new Viewport(workspace);
	}
	
	}catch (Exception e) {
	    e.printStackTrace();
	}

    }

    private void createWorkspace()
    {
	workspace = new Panel();
	workspace.setBorder(false);
	workspace.setPaddings(1);
	workspace.setLayout(new FitLayout());
    }

    private void createBorderPanel()
    {
	borderPanel = new Panel();
	borderPanel.setBorder(false);
	borderPanel.setLayout(new BorderLayout());
    }

    public boolean isSouthPanelVisible()
    {
	return this.addSouth;
    }

    public boolean isEastPanelVisible()
    {
	return this.addEast;
    }

    public boolean isWestPanelVisible()
    {
	return this.addWest;
    }

}
